package com.springboot.study.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * DongGuo
 */
public class HttpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);


    /**
     * Post请求 application/json
     *
     * @param url ： 请求地址
     * @param headerMap ：header参数
     * @param contentMap ： 参数类型
     * @return
     */
    public static String postMap(String url, Map<String,String> headerMap, String contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        // 消息实体
        post.setEntity(new StringEntity(contentMap, "UTF-8"));
        CloseableHttpResponse response = null;
        try {
            // 循环增加header
            Iterator headerIterator = headerMap.entrySet().iterator();
            while(headerIterator.hasNext()){
                Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(),elem.getValue());
            }

            post.addHeader("Content-Type","application/json");
            // 发送请求并接收返回数据
            response = httpClient.execute(post);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                // 获取response的body部分
                HttpEntity entity = response.getEntity();
                // 读取reponse的body部分并转化成字符串
                result = EntityUtils.toString(entity);
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(),e);
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(),e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(),e);
        }catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
        }finally {
            try {
                httpClient.close();
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(),e);
            }
        }
        return null;
    }


    /**
     * Post请求 application/x-www-form-urlencoded
     *
     * @param url 请求地址
     * @param headerMap header参数
     * @param valuePairList
     * @return
     */
    public static String doPost(String url, Map<String,String> headerMap, List<BasicNameValuePair> valuePairList) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            // 循环增加header
            Iterator headerIterator = headerMap.entrySet().iterator();
            while(headerIterator.hasNext()){
                Entry<String,String> elem = (Entry<String, String>) headerIterator.next();
                post.addHeader(elem.getKey(),elem.getValue());
            }
            // 消息实体
            post.setEntity(new UrlEncodedFormEntity(valuePairList, "UTF-8"));
            post.addHeader("Content-Type","application/x-www-form-urlencoded");
            // 发送请求并接收返回数据
            response = httpClient.execute(post);
            if(response != null && response.getStatusLine().getStatusCode() == 200){
                // 获取response的body部分
                HttpEntity entity = response.getEntity();
                // 读取reponse的body部分并转化成字符串
                result = EntityUtils.toString(entity);
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(),e);
        } catch (ClientProtocolException e) {
            LOGGER.error(e.getMessage(),e);
        } catch (IOException e) {
            LOGGER.error(e.getMessage(),e);
        }catch (Exception e) {
            LOGGER.error(e.getMessage(),e);
        }finally {
            try {
                httpClient.close();
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                LOGGER.error(e.getMessage(),e);
            }
        }
        return null;
    }



    /**
     * 发送 GET 请求（HTTP），K-V形式
     *
     * @param url
     * @param params
     * @return
     */
    public static String doGet(String url, Map<String, Object> params) {
        String apiUrl = url;
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : params.keySet()) {
            if (i == 0){
                param.append("?");
            }else {
                param.append("&");
            }
            param.append(key).append("=").append(params.get(key));
            i++;
        }
        apiUrl += param;
        String result = null;
        CloseableHttpClient httpClient =  HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpGet httpPost = null;
        try {
            httpPost = new HttpGet(apiUrl);
            response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                }
            }else{
                //不推荐使用CloseableHttpResponse.close关闭连接，他将直接关闭Socket，导致长连接不能复用
                EntityUtils.consume(response.getEntity());
            }
            return result;
        }catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }finally {
            try {
                if(null != httpClient){
                    httpClient.close();
                }
                if(null != response){
                    response.close();
                }
            } catch (IOException e1) {
                LOGGER.error(e1.getMessage(), e1);
            }
        }
        return result;
    }



}
